package com.rybbaby.tss.platform.tags;

import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;


import com.rybbaby.tss.core.utils.StringUtils;
import com.rybbaby.tss.platform.initializer.SysConfigInitializer;
import freemarker.core.Environment;
import freemarker.template.*;
import org.apache.commons.lang.BooleanUtils;

/**
 * @author 谢进伟
 * @description 系统配置参数读取标签
 * @createDate 2016年11月29日 下午9:04:57
 */
public class SysConfigTag extends BodyTagSupport implements TemplateMethodModelEx, TemplateDirectiveModel {

    private static final long serialVersionUID = -6914740739432385097L;

    /*************************************** 针对freemarker视图的标签实现 ***************************************************/
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        String key = null;
        Object paramValue = params.get("key");
        Object inner = params.get("inner");
        if (paramValue instanceof TemplateScalarModel) {
            key = ((TemplateScalarModel) paramValue).getAsString();
        }
        if (StringUtils.isNotBlank(key)) {
            if (StringUtils.isNotBlank(inner) && BooleanUtils.toBoolean(inner.toString())) {
                loopVars[0] = Configuration.getDefaultObjectWrapper(Configuration.getVersion()).wrap(SysConfigInitializer.getConfigValueByConfigName(key, ""));
                body.render(env.getOut());
            } else {
                Writer out = env.getOut();
                out.write(SysConfigInitializer.getConfigValueByConfigName(key, "") + "");
            }
        }
    }

    @Override
    @SuppressWarnings("rawtypes")
    public Object exec(List arguments) throws TemplateModelException {
        Object key = arguments.get(0);
        if (StringUtils.isNotBlank(key)) {
            Object value = SysConfigInitializer.getConfigValueByConfigName(key.toString(), "");
            return value;
        } else {
            return "";
        }
    }

    /*************************************** 针对jsp视图使的标签实现 ***************************************************/
    /**
     * 资源值key
     **/
    private String key;

    @Override
    public int doEndTag() throws JspException {
        JspWriter out = this.pageContext.getOut();
        try {
            out.print(SysConfigInitializer.getConfigValueByConfigName(key.toString(), ""));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.doEndTag();
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

}
